package com.colorlight.cloud.gateway.core.message.convert;


import com.colorlight.cloud.common.exception.BaseException;
import com.colorlight.cloud.gateway.api.message.constraint.schedule.ScheduleActions;
import com.colorlight.cloud.gateway.api.message.convert.MessageTransition;
import com.colorlight.cloud.gateway.api.message.model.Msg;
import com.google.protobuf.InvalidProtocolBufferException;
import com.iot.proto.gateway.Gateway;
import com.iot.proto.type.ProtocolSummationType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.colorlight.cloud.gateway.core.model.GatewayCoreExceptionEnum.MESSAGE_DECOMPOSITION_EXCEPTION;


/**
 * @author Demon
 *
 */
@Component
@Slf4j
public class MessageTransitionImpl implements MessageTransition {
	
	@Override
	public Gateway.Msg bytesTransFormMessageLite(byte[] bytes) {
		if (Objects.isNull(bytes)) {
			throw new BaseException(MESSAGE_DECOMPOSITION_EXCEPTION);
		}
		Gateway.Msg msg = null;
		try {
			msg = Gateway.Msg.parseFrom(bytes);
		} catch (InvalidProtocolBufferException e) {
			log.error("", e);
		}
		return msg;
	}
	
	@Override
	public Msg<ScheduleActions> toMsg(Gateway.Msg sources, ScheduleActions scheduleActions) {
		String thisName = scheduleActions.getProtocolType().getThisName();
		ProtocolSummationType.NameStruct nameStruct = ProtocolSummationType.NameStruct.valueOf(thisName);
		Msg<ScheduleActions> scheduleActionsMsg = new Msg<>();
		scheduleActionsMsg.setSeqId(sources.getSeqId());
		scheduleActionsMsg.setReplySeqId(sources.getReplySeqId());
		scheduleActionsMsg.setBizContent(scheduleActions.byteConvertObject(sources.getBizContent()));
		scheduleActionsMsg.setTimestamp(sources.getTimestamp());
		scheduleActionsMsg.setVersion(sources.getVersion());
		scheduleActionsMsg.setUuid(sources.getUuid());
		scheduleActionsMsg.setNameStruct(nameStruct);
		return scheduleActionsMsg;
	}
	
}


